package com.gws.ievent.common.utils;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author song
 * @date 2022/10/18 22:23
 */
public class DateTimeUtil {
    public static ZoneOffset zoneOffset = ZoneOffset.of("+8");
    public static String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取毫秒数
     *
     * @param localDateTime
     * @return
     */
    public static long toMillisecond(LocalDateTime localDateTime) {
        return localDateTime.toInstant(zoneOffset).toEpochMilli();
    }


    /**
     * 时间格式化
     *
     * @param dateTime
     * @param pattern
     * @return
     */
    public static LocalDateTime format (String dateTime, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        return LocalDateTime.parse(dateTime, df);
    }


    /**
     * 当期时间格式化: yyyy-MM-dd HH:mm:ss
     *
     * @return
     */
    public static String now() {
        return nowFormat(yyyy_MM_dd_HH_mm_ss);
    }


    /**
     * 当期时间格式化
     *
     * @param pattern
     * @return
     */
    public static String nowFormat(String pattern) {
        return format(new Date(), pattern);
    }


    /**
     * 时间格式化
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        return new SimpleDateFormat(pattern).format(date);
    }


    /**
     * Date 转 LocalDateTime
     * @param date
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date) {
        return date.toInstant().atOffset(zoneOffset).toLocalDateTime();
    }


    /**
     * LocalDateTime 转 Date
     * @param localDateTime
     * @return
     */
    public static Date localDateTime2Date(LocalDateTime localDateTime) {
        return Date.from(localDateTime.toInstant(zoneOffset));
    }

}
